package fr.ants.view;

import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JFrame;

import fr.ants.controller.clock.Clock;
import fr.ants.controller.listener.ButtonsListener;
import fr.ants.controller.listener.FrameListener;
import fr.ants.model.Grid;
import fr.ants.view.component.ToolBar;
import fr.ants.view.panel.MainPanel;

/**
 * Main window of the simulator.
 */
public class MainFrame extends JFrame implements PropertyChangeListener {

	/** Serial UID. */
	private static final long serialVersionUID = -3299185578427993171L;

	/** Window Toolbar */
	private final ToolBar toolBar;

	/** Main panel of the frame. */
	private final MainPanel mainPanel;

	/**
	 * Creates a new window.
	 * 
	 * @param clock clock
	 * @param grid grid
	 */
	public MainFrame(Clock clock, Grid grid) {
		super(HMI.TITLE);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setPreferredSize(new Dimension(900, 900));
		// when the window is closing, we need to stop the simulation
		addWindowListener(new FrameListener(clock));

		// listener for all buttons
		final ButtonsListener buttonsListen = new ButtonsListener(clock, this);

		//Tool bar
		toolBar = new ToolBar(buttonsListen);
		clock.addPropertyChangeListener(toolBar);
		setJMenuBar(toolBar);

		//Main panel
		mainPanel = new MainPanel(buttonsListen, clock);
		buttonsListen.setCanvas(mainPanel.getCanvas());
		mainPanel.getCanvas().addPropertyChangeListener(toolBar);
		setContentPane(mainPanel);

		this.pack();
		this.setVisible(true);
	}

	/**
	 * The window listens to clock events.
	 */
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if ("grid".equals(evt.getPropertyName())) {
			mainPanel.getCanvas().update((Grid) evt.getNewValue());
		}
	}

	public MainPanel getMainPanel() {
		return mainPanel;
	}

}